package cn.edu.zjut.medlinebackend.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.edu.zjut.medlinebackend.mapper.PostMapper;
import cn.edu.zjut.medlinebackend.mapper.UserMapper;
import cn.edu.zjut.medlinebackend.model.Picture;
import cn.edu.zjut.medlinebackend.model.Post;
import cn.edu.zjut.medlinebackend.model.User;
import cn.edu.zjut.medlinebackend.service.FileService;
import cn.edu.zjut.medlinebackend.service.PictureService;
import cn.edu.zjut.medlinebackend.service.PostService;
import cn.edu.zjut.medlinebackend.utils.MyUtils;
import cn.hutool.core.io.FileUtil;
import com.google.gson.Gson;
import net.sourceforge.tess4j.TesseractException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static cn.edu.zjut.medlinebackend.constant.FileConstant.FILE_ROOT_PATH;
import static cn.edu.zjut.medlinebackend.constant.FileConstant.IMG_ROOT_PATH;

@Service
public class FileServiceImpl implements FileService {
    // 改用常量类
//    private static String FILE_ROOT_PATH = ".\\files\\";

    @Resource
    private UserMapper userMapper;

    @Resource
    private PostMapper postMapper;

    @Resource
    private PostService postService;

    @Resource
    private PictureService pictureService;
    
    @Resource
    private PythonServiceImpl pythonService;

    @Resource
    private OcrServiceImpl ocrService;

    @Override
    public boolean uploadFileToDB(String fileName, String tag,HttpServletRequest request) {
        if(fileName == null || fileName.isEmpty()){
            return false;
        }

        if(request == null){
            return false;
        }

        String content;
        String inputFilePath = FILE_ROOT_PATH + "\\" +  fileName;

        try {
            File file = new File(inputFilePath);
            PDDocument document = PDDocument.load(file);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            content = pdfStripper.getText(document);
            System.out.println(content);
            document.close();
        } catch (IOException e) {
            return false;
        }

        String username = MyUtils.getCookieValue(request, "username");
        User byUsername = userMapper.getUserByUsername(username);

        String jsonString = "";
        if(!tag.isEmpty()){
            //将逗号都统一为英文逗号
            String Tag  = tag.replace("，", ","); // 将中文逗号替换为英文逗号
            String[] stringArray=Tag.split(",");// 使用英文逗号作为分隔符拆分字符串
            // 创建一个Gson对象
            Gson gson = new Gson();
            // 使用toJson方法将其转换为JSON字符串
            jsonString = gson.toJson(stringArray);
        }


        Post post = new Post();
        post.setTitle(fileName);
        post.setContent(content);
        post.setTags(jsonString);
        post.setThumbnum(0);
        post.setDislikenum(0);
        post.setDownloadnum(0);
        post.setUserid(byUsername.getId());
        post.setCreatetime(new Date());
        post.setUpdatetime(new Date());
        post.setIsdelete(0);
        int insert = postMapper.insert(post);
        
        // 保存文件中的图片信息
        pythonService.Runpython(fileName);
        File folder = new File(IMG_ROOT_PATH);
        List<String> imgs = FileUtil.listFileNames(String.valueOf(folder)); // 使用Hutool获取文件名列表
        // todo 同名文件会有风险
        imgs = imgs.stream().filter(img -> img.contains(fileName)).collect(Collectors.toList());
        for(String img : imgs){
            File imageFile = new File("img/" + img);
            Picture picture = new Picture();
            try {
                String msg = ocrService.recognizeText(imageFile);
                System.out.println(msg);
                if(!msg.isEmpty()){
                    msg = msg.replaceAll("\\s", " ");
                    picture.setContent(msg);
                    picture.setFileId(post.getId());
                    picture.setUpdatetime(new Date());
                    picture.setImgtitle(img);
                    boolean save = pictureService.save(picture);
                    if(!save){
                        System.out.println("图片保存失败！");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return insert > 0;
    }

    @Override
    public boolean deleteFileByName(String fileName) {

        Post post = postMapper.selectByName(fileName);
        if(post == null){
            System.out.println("文件不存在");
            return false;
        }

        post.setIsdelete(1);

        int update = postMapper.updateById(post);

        return update > 0;
    }
}
